package com.lagou.user.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lagou.entity.User;
import com.lagou.entity.UserDTO;
import com.lagou.user.UserService;

import entity.FileSystem;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: lagou-edu-web
 * @Author: GuoAn.Sun
 * @CreateTime: 2020-09-08 11:22
 * @Description:
 */

@RestController
@RequestMapping("user")
public class UserController {

    @Reference // 远程消费
    private UserService userService;

    @GetMapping("login")
    public UserDTO login(String phone, String password,String nickname,String headimg) {
        UserDTO dto = new UserDTO();
        User user = null;
        System.out.println("phone = " + phone);
        System.out.println("password = " + password);
        System.out.println("nickname = " + nickname);

        // 检测手机号是否注册
        Integer i = userService.checkPhone(phone);
        if(i == 0){
            // 未注册，自动注册并登录
            userService.register(phone, password,nickname,headimg);
            dto.setMessage("手机号尚未注册，系统已帮您自动注册，请牢记密码！");
            user = userService.login(phone, password);
        }else{
            user = userService.login(phone, password);
            if(user == null){
                dto.setState(300); //300表示失败
                dto.setMessage("帐号密码不匹配，登录失败！");
            }else{
                dto.setState(200); //200表示成功
                dto.setMessage("登录成功！");
            }
        }

        dto.setContent(user);
        return dto;
    }

    @RequestMapping("upload")
    //MultipartHttpServletRequest：是httpservletRequest的强化版本，不仅可以装文本信息，还可以装图片文件信息
    public @ResponseBody
    FileSystem upload(MultipartHttpServletRequest request) throws Exception {
        FileSystem fileSystem = new FileSystem();

        /* 1、把文件保存到web服务器*/

        // 从页面请求中，获取上传的文件对象
        MultipartFile file = request.getFile("fname");
        // 从文件对象中获取 文件的原始名称
        String oldFileName = file.getOriginalFilename();
        // 通过字符串截取的方式，从文件原始名中获取文件的后缀   1.jpg
        String hou = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
        // 为了避免文件因为同名而覆盖，生成全新的文件名
        String newFileName = UUID.randomUUID().toString() + "." + hou;
        // 创建web服务器保存文件的目录(预先创建好D:/upload目录，否则系统找不到路径，会抛异常)
        File toSaveFile = new File("D:/upload/" + newFileName);
        // 将路径转换成文件
        file.transferTo(toSaveFile);
        // 获取服务器的绝对路径
        String newFilePath = toSaveFile.getAbsolutePath();

        /* 2、把文件从web服务器上传到FastDFS*/

        ClientGlobal.initByProperties("config/fastdfs-client.properties");
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient1 client = new StorageClient1(trackerServer, storageServer);

        NameValuePair[] list = new NameValuePair[1];
        list[0] = new NameValuePair("fileName",oldFileName);
        String fileId = client.upload_file1(newFilePath, hou, list);
        trackerServer.close();

        // 封装fileSystem数据对象
        fileSystem.setFileId(fileId);
        fileSystem.setFileName(oldFileName);
        fileSystem.setFilePath(fileId);  //已经上传到FastDFS上，通过fileId来访问图片，所以fileId即为文件路径

        return  fileSystem;
    }


    //修改昵称
    @RequestMapping("updateUserInfo")
    @ResponseBody
    public UserDTO updateUserInfo(@RequestBody User user){
        System.out.println(user.getId());
        System.out.println(user.getName());
        System.out.println(user.getName());
        UserDTO<User> userDTO=new UserDTO<>();
        Integer i = userService.updateUserInfo(user.getId(),user.getName(),user.getPortrait());
        if(i>0){
            userDTO.setState(200);
            userDTO.setMessage("修改成功");
            userDTO.setContent(null);
        }else {
            userDTO.setState(300);
            userDTO.setMessage("修改失败");
            userDTO.setContent(null);
        }
        return userDTO;
    }


    //修改密码
    @RequestMapping("updatePassword")
    @ResponseBody
    public UserDTO updatePassword(@RequestBody User user){
        System.out.println(user.getId());
        System.out.println(user.getPassword());
        Integer i = userService.updatePassword(user.getId(), user.getPassword());
        UserDTO userDTO=new UserDTO();
        if(i>0){
            userDTO.setState(200);
            userDTO.setMessage("修改成功");
            userDTO.setContent(null);
        }else {
            userDTO.setState(300);
            userDTO.setMessage("修改失败");
            userDTO.setContent(null);
        }
        return userDTO;
    }

}



